// pages/cart/index.js
import {request} from '../../request/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    cart:{},
    totalPrice:0,
    totalNum:0
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let address=wx.getStorageSync('address');
    //获取缓存中的数据
    let cart=wx.getStorageSync('cart')||[];
    cart=cart.filter(v=>v.checked)
    this.setData({address})
    let totalPrice=0;
    let totalNum=0;
    cart.forEach(v=>{
        totalPrice+=v.num*v.goodsPrice;
        totalNum+=v.num
    })
    this.setData({cart,totalPrice,totalNum,address})
  },
  //模拟支付
  handlePlay(){
     let token=wx.getStorageSync('token');
     if(!token){
       wx.navigateTo({
         url: '/pages/auth/index',
       })
       return ;
     }
     console.log(this.data.address.provinceName)
     let orderPrice=this.data.totalPrice;
     let phone=this.data.address.telNumber;
     let postalCode=this.data.address.postalCode;
     let userName=this.data.address.userName;
     let addressAll=this.data.address.provinceName+this.data.address.cityName+this.data.address.countyName+this.data.address.detailInfo;
     let orderGoods=[];
     let cart=wx.getStorageSync('cart')||[];
     cart.forEach(v=>orderGoods.push(
       {goodsId: v.goodsId,
        num:v.num,
        goodsPrice:v.goodsPrice}
     ))
     request({url:"http://localhost:8002/wx/order/save",header: { 
      "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
      "Authorization":wx.getStorageSync('token')
     },method:"POST",data:{orderPrice:orderPrice,phone:phone,postalCode:postalCode,userName:userName,addressAll:addressAll,orderGoods:JSON.stringify(orderGoods)}}).then(res=>{
      //  支付成功后 删除选中的商品
      console.log(res)
         
       let cart=wx.getStorageSync('cart');
       cart=cart.filter(v=>!v.checked)
       wx.setStorageSync('cart', cart);
       wx.switchTab({
        url: '/pages/cart/index',
      })
      wx.showToast({
        duration: 2000,
        icon:"success",
        title: '支付成功',
       })
      }
     )
  }
})